package com.geostar.constructionland.common.util;


import info.monitorenter.cpdetector.io.*;
import org.springframework.web.multipart.MultipartFile;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件格式工具
 */
public class FileCharsetUtil {
    /**
     * 获取文件格式名称
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getFileCharsetName(String fileName) throws Exception{
        InputStream inputStream = new FileInputStream(fileName);
        byte[] head = new byte[3];
        inputStream.read(head);

        String charsetName = "GBK";//或GB2312，即ANSI
        if (head[0] == -1 && head[1] == -2 ) //0xFFFE
            charsetName = "UTF-16";
        else if (head[0] == -2 && head[1] == -1 ) //0xFEFF
            charsetName = "Unicode";//包含两种编码格式：UCS2-Big-Endian和UCS2-Little-Endian
        else if(head[0]==-27 && head[1]==-101 && head[2] ==-98)
            charsetName = "UTF-8"; //UTF-8(不含BOM)
        else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
            charsetName = "UTF-8"; //UTF-8-BOM

        inputStream.close();
        return charsetName;
    }

    /**
     * 获取文件格式名称
     * @return
     * @throws Exception
     */
    public static String getFileCharsetNameByMultipartFile(MultipartFile multipartFile) throws Exception{
        InputStream inputStream = multipartFile.getInputStream();
        byte[] head = new byte[3];
        inputStream.read(head);

        String charsetName = "GBK";//或GB2312，即ANSI
        if (head[0] == -1 && head[1] == -2 ) //0xFFFE
            charsetName = "UTF-16";
        else if (head[0] == -2 && head[1] == -1 ) //0xFEFF
            charsetName = "Unicode";//包含两种编码格式：UCS2-Big-Endian和UCS2-Little-Endian
        else if(head[0]==-27 && head[1]==-101 && head[2] ==-98)
            charsetName = "UTF-8"; //UTF-8(不含BOM)
        else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
            charsetName = "UTF-8"; //UTF-8-BOM

        inputStream.close();
        return charsetName;
    }
}
